import requests
import urllib
import json
from django.conf import settings
from django_redis import get_redis_connection


import logging

logger = logging.getLogger(__name__)


# from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


# ================================================
#
# 小程序部分
#
# ================================================
class requests_SDK(requests.Session):
    """微信小程序"""

    Conf = {"status": 0}

    def getConf(self):
        try:
            with open(settings.CONF / "wechat.json", "r") as fs:
                code = fs.read()
                dictcode = json.loads(code)
        except BaseException as err:
            print(err)
            self.Conf = {"status": 0}
        else:
            self.Conf = dictcode

    def has_headers(self):
        return self.headers

    def has_access_token(self):
        x = get_redis_connection("sysconf").get("apps_access_token")
        token = x if x else self.yisbar_token()
        return token

    def yisbar_token(self):
        headers = {"Content-Type": "application/json"}
        try:
            r = self.get(
                url="https://api.yisbar.com/hasToken/",
                headers=headers,
                verify=False,
            )
            print(r.text)
            return r.json().get("WxToken", "") if r and r.status_code == 200 else ""
        except BaseException as err:
            return ""

    def get_token(self):
        url = "/cgi-bin/token"
        headers = self.has_headers()
        headers["Content-Type"] = "application/json"
        params = {
            "grant_type": "client_credential",
            "appid": self.Conf.get("appid"),
            "secret": self.Conf.get("secret"),
        }

        token = self.do_get(url, headers=headers, params=params)
        print("微信小程序token请求GET", token)
        if not token or token.get("errcode"):
            return None

        get_redis_connection("sysconf").set(
            "apps_access_token", token.get("access_token")
        )
        get_redis_connection("sysconf").expire(
            "apps_access_token", token.get("expires_in")
        )
        return token.get("access_token")

    def post_token(self):
        url = "/cgi-bin/stable_token"  # 稳定版
        headers = self.has_headers()
        headers["Content-Type"] = "application/json"
        data = {
            "grant_type": "client_credential",
            "appid": self.Conf.get("appid"),
            "secret": self.Conf.get("secret"),
            # "force_refresh": False,
        }
        token = self.do_post(url, headers=headers, data=data)
        print("微信小程序token请求POST", token)
        if not token or token.get("errcode"):
            return None
        get_redis_connection("sysconf").set(
            "apps_access_token", token.get("access_token")
        )
        get_redis_connection("sysconf").expire(
            "apps_access_token", token.get("expires_in")
        )
        return token.get("access_token")

    def do_get(self, url="", headers=None, params=None, data=None):
        if not self.Conf.get("status"):
            return None
        url = self.Conf.get("host") + url
        try:
            r = self.get(url, headers=headers, params=params, data=data, verify=False)
            logger.info(f"模板消息: [GET] [{r.text}] [{data}]")
            return r.json() if r and r.status_code == 200 else None
        except BaseException as err:
            return None

    def do_post(self, url="", headers=None, params=None, data=None, json=None):
        if not self.Conf.get("status"):
            return None
        url = self.Conf.get("host") + url
        try:
            r = self.post(
                url, headers=headers, params=params, data=data, json=json, verify=False
            )
            logger.info(f"模板消息: [POST] [{r.text}] [{data}]")
            return r.json() if r and r.status_code == 200 else None
        except BaseException as err:
            return None


# ================================================
#
# 公众号部分
#
# ================================================
class requests_Wechat_SDK(requests.Session):
    """微信公众号"""

    Conf = {"status": 0}

    def getConf(self):
        try:
            with open(settings.CONF / "wechat.json", "r") as fs:
                code = fs.read()
                dictcode = json.loads(code)
        except BaseException as err:
            print(err)
            self.Conf = {"status": 0}
        else:
            self.Conf = dictcode

    def has_headers(self):
        return self.headers

    def has_access_token(self):
        x = get_redis_connection("sysconf").get("chat_access_token")
        token = x if x else self.yisbar_token()
        return token

    def yisbar_token(self):
        headers = {"Content-Type": "application/json"}
        try:
            r = self.get(
                url="https://api.yisbar.com/hasMppdToken/",
                headers=headers,
                verify=False,
            )
            return r.json().get("WxToken", "") if r and r.status_code == 200 else ""
        except BaseException as err:
            return ""

    def get_token(self):
        url = "/cgi-bin/token"
        headers = self.has_headers()
        headers["Content-Type"] = "application/json"
        params = {
            "grant_type": "client_credential",
            "appid": self.Conf.get("weappid"),
            "secret": self.Conf.get("wesecret"),
        }
        token = self.do_get(url, headers=headers, params=params)
        print("微信公众号token请求GET", token)
        if not token or token.get("errcode"):
            return None

        get_redis_connection("sysconf").set(
            "chat_access_token", token.get("access_token")
        )
        get_redis_connection("sysconf").expire(
            "chat_access_token", token.get("expires_in")
        )
        return token.get("access_token")

    def post_token(self):
        url = "/cgi-bin/stable_token"  # 稳定版
        headers = self.has_headers()
        headers["Content-Type"] = "application/json"
        data = {
            "grant_type": "client_credential",
            "appid": self.Conf.get("weappid"),
            "secret": self.Conf.get("wesecret"),
        }
        token = self.do_post(url, headers=headers, data=data)
        print("微信公众号token请求POST", token)
        if not token or token.get("errcode"):
            return None

        get_redis_connection("sysconf").set(
            "chat_access_token", token.get("access_token")
        )
        get_redis_connection("sysconf").expire(
            "chat_access_token", token.get("expires_in")
        )
        return token.get("access_token")

    def do_get(self, url="", headers=None, params=None, data=None):
        if not self.Conf.get("status"):
            return None
        url = self.Conf.get("host") + url
        try:
            r = self.get(url, headers=headers, params=params, data=data, verify=False)
            logger.info(f"模板消息: [GET] [{r.text}] [{data}]")
            return r.json() if r and r.status_code == 200 else None
        except BaseException as err:
            return None

    def do_post(self, url="", headers=None, params=None, data=None, json=None):
        if not self.Conf.get("status"):
            return None
        url = self.Conf.get("host") + url
        try:
            r = self.post(
                url, headers=headers, params=params, data=data, json=json, verify=False
            )
            logger.info(f"模板消息: [POST] [{r.text}] [{data}]")
            return r.json() if r and r.status_code == 200 else None
        except BaseException as err:
            return None


# 实例化小程序接口
# WX = requests_SDK()
# WX.getConf()

# 实例化公众号接口
# WECHAT = requests_Wechat_SDK()
# WECHAT.getConf()
